﻿using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Common.Serialization;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Lang;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Script;
using ZyGames.Framework.Net;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 10046离开房间
	/// </summary>
	public class Action10046 : BaseAction
	{
		private int tableId;
		private int userId;
		private GameUser _currentGameUser;
		private TableData _currentTable;
		private bool result = false;
		public Action10046(HttpGet actionGetter)
			: base((short)ActionType.DZLeaveRoom, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableID", ref tableId) &&
				httpGet.GetInt("UserID", ref userId))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			_currentGameUser = GameTable.Current.GetUser(userId);
			if (_currentGameUser == null)
			{
				ErrorCode = Language.Instance.ErrorCode;
				return false;
			}
			_currentTable = GameRoom.Current.GetTableData(tableId);
			if (_currentTable == null)
			{
				Tool.WriteErrorLine("消息10045获得房间不存在");
				return false;
			}

			//个人信息删除这个房间， 房间里删除这个人信息
			int posId = -1;
			if (_currentGameUser.Property.PositionId.TryGetValue(tableId, out posId))
			{
				if (posId > 0)
				{
					Tool.WriteErrorLine("消息10045 玩家的座位不为0, 还在坐下状态，不好离开房间");
					this.result = false;
					return false;
				}
			}
			
			//广播10047
			var parameters = new Parameters();
			parameters["TableID"] = tableId;
			parameters["UserID"] = userId;
			GameTable.Current.SyncNotifyAction((int)ActionType.DZBrocastLeaveRoom, _currentTable, parameters, t =>
			{
				Tool.WriteLine("广播10047某人离开房间");
			});
			
			this.result = true;
			return true;
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this.result);
			if(result)
			{
				//桌子删除掉这个人
				_currentTable.PlayersData.Remove(_currentGameUser);

				//离开房间
				_currentGameUser.Property.TableIdList.Remove(tableId);
				_currentGameUser.Property.PositionId.Remove(tableId);
			}
		}
	}
}
